from django.db.models import F
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet,GenericViewSet
from rest_framework.mixins import CreateModelMixin,DestroyModelMixin
from community.models import Article
from rest_framework.permissions import IsAuthenticated

from utils.permission import *
from .serializers import *
from rest_framework.pagination import PageNumberPagination


class ArticlePaginationPageNumber(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'size'
    max_page_size = 100


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.filter(is_delete=False)
    serializer_class = ArticleSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = ArticlePaginationPageNumber

    def get_queryset(self):
        if self.action in ['list', 'retrieve']:
            return Article.objects.filter(is_delete=False, status=1)
        return self.queryset

    @auto_user
    def create(self, request, *args, **kwargs):
        return ModelViewSet.create(self, request, *args, **kwargs)

    @update_auto_user
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)

    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        return ModelViewSet.destroy(self, request, *args, **kwargs)

    @action(methods=['get'], detail=False)
    def my(self, request):
        data = self.get_queryset().filter(user=request.user)
        serializer = self.get_serializer(data, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        self.get_queryset().filter(id=kwargs['pk']).update(page_view=F('page_view') + 1)
        return ModelViewSet.retrieve(self, request, *args, **kwargs)

    @action(methods=['get'], detail=True)
    def comment(self, request, pk):
        comments = Comment.objects.filter(article_id=pk, level=1)
        serializer = CommentSerializer(comments, many=True)
        return Response(serializer.data)


class CommentViewSet(GenericViewSet, CreateModelMixin, DestroyModelMixin):
    queryset = Comment.objects.filter(is_delete=False, article__status=1)
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticated]

    # @auto_user
    def create(self, request, *args, **kwargs):
        return CreateModelMixin.create(self, request, *args, **kwargs)

    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        return DestroyModelMixin.destroy(self, request, *args, **kwargs)
